<template>
  <div class="roles-wrapper">
    <div class="roles-body">
      <div class="tabsBox sTabsBox">
        <div class="roleFn">
          <span class="roleBtn" @click="addRoleGroupModal = true">新增角色组</span>
          <span class="roleBtn" @click="addRoleBtn(0)">新增角色</span>
        </div>
        <el-tree
          class="roleTree"
          :data="roleTreeData"
          node-key="roleId"
          default-expand-all
          @node-click="openRoleDetails"
          :expand-on-click-node="false"
          :props="defaultProps1">
          <div class="custom-tree-node"
            slot-scope="{ node, data }"
            :class="{active: data.roleId === currentRoleInfo.roleId}">
            <span>{{ node.label }}</span>
            <span v-show="!data.roleCode"
                  class="iconfont editIcon"
                  style='font-size:10px;'
                  @click='editRoleGroup(data)'>
              &#xe650;
            </span>
            <!-- <span v-show="!data.roleCode && data.isPersist !== 1"
                  class="iconfont editIcon"
                  style='font-size:10px;'
                  @click='editRoleGroup(data)'>
              &#xe650;
            </span> -->
          </div>
        </el-tree>
      </div>
      <div class="rightPart">
        <!-- 角色部分 -->
        <div class="role">
          <!-- 上方列表 -->
          <div class="roleListTop">
            <div class="title">
              <div class="editBox">
                <i class="el-icon-user-solid" type="md-person" color="#afe4fa"></i>
                <div style="lineHeight: 30px; marginRight: 7px; fontSize: 14px">{{currentRoleInfo.roleName}} （{{totalR}}人）
                  <div
                    class="editBtn"
                    @click="addRoleBtn(1)">编辑</div>
                  <!-- <div
                    class="editBtn"
                    v-show="currentRoleInfo.isDefault === 0"
                    @click="addRoleBtn(1)">编辑</div>
                  <div
                    v-show="currentRoleInfo.isDefault === 1"
                    class="editBtn"
                    @click="addRoleBtn(2)">查看</div> -->
                </div>
              </div>
            </div>
          </div>
          <!-- 下方列表 -->
          <div class="role-cont">
            <div class="handle">
              <div class="handle-left">
                <!-- <type-button @handleClick="startAddUser" size='small' type='add'></type-button> -->
                <type-button
                  size='small'
                  type='add'
                  @handleClick="showAddMember()">
                </type-button>
                <type-button
                  class="btn ml16"
                  :disabled="delRoleStaffIds.length === 0"
                  size='small'
                  title="移除"
                  type="delete"
                  @handleClick="selectRemove()">
                </type-button>
                <!-- <type-button
                  class="btn ml20"
                  :disabled="delRoleStaffIds.length === 0"
                  size='small'
                  title="删除"
                  type="delete"
                  @handleClick="selectDel()">
                </type-button> -->
                <!-- <type-button @handleClick="exportFile" class="btn" size='small' type='export'></type-button> -->
              </div>
              <div class="handle-right">
                <span class="search-input-box">
                  <el-input
                    type="text"
                    clearable
                    placeholder='请输入用户姓名'
                    v-model='searchInfo.roleInputValue'>
                  </el-input>
                </span>
                <span class="search-select-box ml16">
                  <el-select
                    clearable
                    filterable
                    v-model="searchInfo.tenantId"
                    placeholder="请选择租户">
                    <el-option v-for='item in tenantList'
                      :key='item.tenantId'
                      :label='item.tenantName'
                      :value='item.tenantId'>
                    </el-option>
                  </el-select>
                </span>
                <span class="search-btn ml16"
                  @click="handleRoleSearch()">查询</span>
              </div>
            </div>
            <div class="role-table">
              <section class="table-wrapper" :style='{height: tableHeight2}'>
                <el-table
                  :data="currentRoleStaff"
                  height='100%'
                  stripe
                  @selection-change="selectionChange"
                  style="width: 100%">
                  <el-table-column
                    show-overflow-tooltip
                    min-width='50'
                    type="selection">
                  </el-table-column>
                  <el-table-column show-overflow-tooltip
                                prop="name"
                                min-width='80'
                                label="姓名">
                  </el-table-column>
                  <el-table-column show-overflow-tooltip
                              prop="tenantName"
                              min-width='120'
                              label="租户">
                  </el-table-column>
                  <el-table-column show-overflow-tooltip
                                    prop="account"
                                    min-width='110'
                                    label="手机">
                  </el-table-column>
                  <el-table-column show-overflow-tooltip
                                    prop="email"
                                    min-width='150'
                                    label="邮箱">
                  </el-table-column>
                  <el-table-column show-overflow-tooltip
                                    prop="wechaId"
                                    min-width='150'
                                    label="微信号">
                  </el-table-column>
                  <el-table-column show-overflow-tooltip
                                    prop="roleName"
                                    min-width='110'
                                    label="角色">
                  </el-table-column>
                  <el-table-column
                    fixed="right"
                    label="操作"
                    width='120'>
                    <template slot-scope="scope">
                      <!-- <span class="handleBtn" @click="handleEdit(scope.row)">编辑</span> -->
                      <!-- <span class="handleBtn" @click="handleDelete(scope.row)">删除</span> -->
                      <span class="handleBtn" @click="handleRemove(scope.row)">移除</span>
                    </template>
                  </el-table-column>
                </el-table>
              </section>
              <el-pagination
                background
                v-show='currentRoleStaff.length'
                style="width: 100%; text-align: center"
                :page-sizes="[8]"
                :page-size="pageSizeR"
                :current-page="pageR"
                @current-change="handleCurrentChangeR"
                layout="sizes, prev, pager, next"
                :total="totalR">
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="add-diolog">
      <!-- 添加角色组 -->
      <drawer
        :size="'50%'"
        :title="'添加角色组'"
        :visible="addRoleGroupModal"
        @beforeClose="beforeClose('addRoleGroupModal')"
        @closeDrawer="clearAddRoleFields">
        <div slot="body" class="personal-wrapper">
          <div class="title">角色组信息</div>
          <el-form  :model="addRoleGroup"
                    ref="addRoleGroup"
                    label-width="134px"
                    class="demo-ruleForm">
            <el-form-item label="角色组名称"
                          prop="addRoleGroupName"
                          :rules="[
                          { required: true, message: '请输入角色组名称', trigger: 'blur' }
                        ]"
                          >
              <el-input
                maxlength="10"
                show-word-limit
                placeholder="请输入角色组名称"
                v-model.trim="addRoleGroup.addRoleGroupName">
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <template slot="footer">
          <el-button size="small" type="primary" @click="addRoleGroupSaveBtn">保 存</el-button>
          <el-button size="small" @click="addRoleGroupModal = false">取 消</el-button>
        </template>
      </drawer>
      <!-- 编辑角色组 -->
      <drawer
        :size="'50%'"
        :title="'编辑角色组'"
        :visible="editRoleGroupModal"
        @beforeClose="beforeClose('editRoleGroupModal')">
        <div slot="body" class="personal-wrapper">
          <div class="title">角色组信息</div>
          <el-form  :model="editingRoleGroup"
                    ref="editingRoleGroup"
                    label-width="134px"
                    class="demo-ruleForm">
            <el-form-item label="角色组名称"
                          prop="roleName"
                          :rules="[
                          { required: true, message: '请输入角色组名称', trigger: 'blur' }
                        ]"
                          >
              <el-input
                maxlength="10"
                show-word-limit
                placeholder="请输入角色组名称"
                v-model.trim="editingRoleGroup.roleName">
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <template slot="footer">
          <el-button size="small" type="primary" @click="editRoleGroupSaveBtn">保 存</el-button>
          <el-button size="small" @click='initRoleGroupDialog'>取 消</el-button>
          <el-button size="small" type="danger" style="padding:8px 16px;" plain @click="delRoleGroupBtn" v-show= 'editingRoleGroup.roleGroupCode !== "001"'>删 除</el-button>
        </template>
      </drawer>
      <!-- 添加/编辑/查看角色 -->
      <drawer
        :size="'50%'"
        :title="roleModalText"
        :visible="addRoleModal"
        @beforeClose="beforeClose('addRoleModal')"
        @closeDrawer="resetEmployeeInfo">
        <div
          v-if="addRoleModal"
          slot="body"
          class="personal-wrapper">
          <el-form  :model="addRole"
                    ref="addRole"
                    label-width="114px"
                    class="demo-ruleForm">
            <el-form-item
              label="角色名称"
              prop="addRoleName"
              :rules="[
                { required: true, message: '请输入角色名称', trigger: 'blur' }
              ]">
              <el-input
                :maxlength="10"
                show-word-limit
                placeholder="请输入角色名称"
                :readonly="banEdit"
                v-model.trim="addRole.addRoleName">
              </el-input>
            </el-form-item>
            <el-form-item
              label="分组到"
                prop="roleGroupId"
                :rules="[
                  { required: true, message: '请选择角色组', trigger: 'change' }
                ]">
              <el-select
                v-model="addRole.roleGroupId"
                :disabled="banEdit"
                @change="getCurrentRoleGroupIdFn"
                placeholder="请选择">
                <el-option
                  v-for="item in roleGroupList"
                  :key="item.roleGroupId"
                  :label="item.roleGroupName"
                  :value="item.roleGroupId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="菜单分配" prop="menuList">
              <div class="menu-wrapper">
                <el-radio-group v-model="menuType" size="small">
                  <el-radio-button label="wechat">营销平台</el-radio-button>
                  <el-radio-button label="enterprise">企微平台</el-radio-button>
                  <el-radio-button label="system">运维平台</el-radio-button>
                </el-radio-group>
                <ul class="tree-list">
                  <li class="tree-item"
                    v-show="menuType === 'wechat'">
                    <el-tree
                      ref="wechatTreeRef"
                      node-key="menuId"
                      show-checkbox
                      highlight-current
                      default-expand-all
                      :props="defaultProps2"
                      :data="wechatMenuList"
                      @check="checkWechatMenuList">
                    </el-tree>
                  </li>
                  <li class="tree-item"
                    v-show="menuType === 'enterprise'">
                    <el-tree
                      ref="corpTreeRef"
                      node-key="menuId"
                      show-checkbox
                      highlight-current
                      default-expand-all
                      :props="defaultProps2"
                      :data="corpMenuList"
                      @check="checkCorpMenuList">
                    </el-tree>
                  </li>
                  <li class="tree-item"
                    v-show="menuType === 'system'">
                    <el-tree
                      ref="systemTreeRef"
                      node-key="menuId"
                      show-checkbox
                      highlight-current
                      default-expand-all
                      :props="defaultProps2"
                      :data="systemMenuList"
                      @check="checkSystemMenuList">
                    </el-tree>
                  </li>
                </ul>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <template slot="footer">
          <template v-if="!banEdit">
            <el-button size="small" type="primary" @click="addRoleSaveBtn()">保 存</el-button>
            <el-button size="small" @click="addRoleModal = false">取 消</el-button>
            <el-button size="small" v-show="banFlag" type="danger" plain @click="delRoleBtn()">删 除</el-button>
          </template>
          <template v-else>
            <type-button size="small" type="back" @handleClick="addRoleModal = false"></type-button>
          </template>
        </template>
      </drawer>
      <!-- 账户 -->
      <drawer size='700px'
            :title='mode === "create" ? "添加账户" : "编辑账户"'
            :visible="isEditAccount"
            @beforeClose="beforeClose('isEditAccount')"
            @closeDrawer="clearAddUserFields">
        <div slot="body" class="add-staff personal-wrapper">
          <!-- 添加账户 -->
          <div v-show='mode === "create"'>
            <el-form :model="newAccount"
                    :rules="addRules"
                    ref="addStaff"
                    label-width="104px"
                    class="demo-ruleForm">
              <el-form-item label="姓名" prop="name">
                <el-input placeholder="请输入姓名"
                          v-model.trim="newAccount.name">
                </el-input>
              </el-form-item>
              <el-form-item label="账号" prop="account">
                <el-input placeholder="请输入账号"
                          v-model.trim="newAccount.account"
                          oninput="this.value=this.value.replace(/\D/g,'')"
                          maxlength="11">
                </el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input
                  placeholder="请输入密码"
                  v-model.trim="newAccount.password"
                  show-password>
                </el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="passwords">
                <el-input
                  placeholder="请再次输入密码"
                  v-model.trim="newAccount.passwords"
                  show-password>
                </el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input placeholder="请输入邮箱"
                          v-model.trim="newAccount.email">
                </el-input>
              </el-form-item>
              <el-form-item label="角色" prop="posOption">
                <el-select v-model="newAccount.posOption"
                          multiple
                          placeholder="请选择">
                  <el-option v-for="item in posOptions"
                            :key="item.roleId"
                            :label="item.roleName"
                            :value="item.roleId">
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="员工" prop="userId">
                <el-select v-model="newAccount.userId"
                          placeholder="请选择">
                  <el-option v-for="item in empList"
                            :key="item.userId"
                            :label="item.userName"
                            :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item> -->
            </el-form>
          </div>
          <!-- 编辑账户 -->
          <div v-show='mode === "edit"'>
            <el-form :model="accountData"
                    :rules="editRules"
                    ref="editStaff"
                    label-width="104px"
                    class="demo-ruleForm">
              <el-form-item label="姓名" prop="name">
                <el-input placeholder="请输入姓名"
                          v-model.trim="accountData.name">
                </el-input>
              </el-form-item>
              <el-form-item label="账号" prop="account">
                <el-input placeholder="请输入账号"
                          :disabled="true"
                          v-model.trim="accountData.account"
                          oninput="this.value=this.value.replace(/\D/g,'')"
                          maxlength="11">
                </el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input
                  placeholder="输入密码进行修改"
                  v-model.trim="accountData.password"
                  show-password>
                </el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="passwords">
                <el-input placeholder="请再次输入修改密码"
                          v-model.trim="accountData.passwords"
                          show-password>
                </el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input placeholder="请输入邮箱"
                          v-model.trim="accountData.email">
                </el-input>
              </el-form-item>
              <el-form-item label="角色" prop="posOption">
                <el-select v-model="accountData.posOption"
                          multiple
                          placeholder="请选择">
                  <el-option v-for="item in posOptions"
                            :key="item.roleId"
                            :label="item.roleName"
                            :value="item.roleId">
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="员工" prop="userId">
                <el-select v-model="accountData.userId"
                          placeholder="请选择">
                  <el-option v-for="item in empList"
                            :key="item.userId"
                            :label="item.userName"
                            :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item> -->
            </el-form>
          </div>
        </div>
        <template slot="footer">
          <el-button size="small" type="primary" @click="saveAccount">确 定</el-button>
          <el-button size="small" @click="isEditAccount = false">取 消</el-button>
        </template>
      </drawer>
      <!-- 给某个角色添加成员 -->
      <drawer
        size='870px'
        title="添加成员"
        :visible="isShowAddMeber"
        @beforeClose="beforeClose('isShowAddMeber')"
        @closeDrawer="resetMember">
        <div slot="body" class="account-body">
          <section class="account-top">
            <div class='filter-left'>
              <span class="search-input-box">
                <el-input
                  type="text"
                  clearable
                  placeholder='请输入用户姓名'
                  v-model='searchInfo2.name'>
                </el-input>
              </span>
              <span class="search-select-box ml16">
                <el-select
                  clearable
                  filterable
                  v-model="searchInfo2.tenantId"
                  placeholder="请选择租户">
                  <el-option v-for='item in tenantList'
                    :key='item.tenantId'
                    :label='item.tenantName'
                    :value='item.tenantId'>
                  </el-option>
                </el-select>
              </span>
              <span class="search-btn ml16"
                @click="handleUserSearch()">查询</span>
            </div>
            <div class="filter-right"></div>
          </section>
          <div class="table-wrapper">
            <section>
              <el-table
                ref="accountListRef"
                :data="accountList"
                tooltip-effect='light'
                :row-key="(row)=>{ return row.accountId}"
                @selection-change="handleSelectionChange">
                <el-table-column
                  type="selection"
                  :reserve-selection="true"
                  width="55">
                </el-table-column>
                <el-table-column show-overflow-tooltip
                                  prop="name"
                                  min-width='80'
                                  label="姓名">
                </el-table-column>
                <el-table-column show-overflow-tooltip
                            prop="tenantName"
                            min-width='120'
                            label="租户">
                </el-table-column>
                <el-table-column show-overflow-tooltip
                                  prop="account"
                                  min-width='110'
                                  label="手机">
                </el-table-column>
                <el-table-column show-overflow-tooltip
                                  prop="email"
                                  min-width='150'
                                  label="邮箱">
                </el-table-column>
                <el-table-column show-overflow-tooltip
                                  prop="wechaId"
                                  min-width='150'
                                  label="微信号">
                </el-table-column>
                <el-table-column show-overflow-tooltip
                                  prop="roleName"
                                  min-width='110'
                                  label="角色">
                </el-table-column>
              </el-table>
            </section>
            <el-pagination
                style="width:100%;text-align:center;"
                background
                v-show='accountList.length'
                :total="countUser"
                :current-page="pageUser"
                :page-size="pageSizeUser"
                :page-sizes="pageSizesG"
                @size-change="handleSizeUserChange"
                @current-change="handleCurrentUserChange"
                layout="sizes, prev, pager, next">
              </el-pagination>
          </div>
        </div>
        <template slot="footer">
          <el-button
            size="small"
            type="primary"
            @click="saveAddMember()">确 定</el-button>
          <el-button
            size="small"
            @click="isShowAddMeber = false">取 消</el-button>
        </template>
      </drawer>
    </div>
  </div>
</template>
<script>
import TypeButton from '@/public/typeButton'
import searchInput from 'public/search-input'
import Drawer from '@/public/Drawer'
export default {
  name: 'rolesList',
  components: {
    TypeButton,
    searchInput,
    Drawer
  },
  data () {
    var checkTel = (rule, value, callback) => {
      if (!value) {
        callback(new Error('必填'))
      } else if (value) {
        let re = /^1\d{10}$/
        let result = re.test(value)
        if (!result) {
          callback(new Error('手机号码不正确'))
        } else {
          callback()
        }
      }
    }
    var validateEmail = (rule, value, callback) => {
      /* eslint-disable no-useless-escape */
      let res = /\w+((-w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+/
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (!res.test(value)) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      isLoading: false, // 防抖
      banFlag: false, // 区分添加和编辑
      banEdit: false, // 区分添加、编辑和查看
      roleModalText: '',
      editEmpId: '',
      editUserId: '',
      roleGroupRoleList: [],
      roleGroupList: [],
      defaultProps1: {
        children: 'children',
        label: 'roleName'
      },
      addRoleGroupModal: false,
      addRoleGroup: {
        addRoleGroupName: null
      },
      addRoleModal: false,
      addRole: {
        addRoleName: null,
        roleId: null,
        roleGroupId: null,
        parentRoleId: null,
        // menuList: []
        chooseWechatMenuList: [],
        chooseCorpMenuList: [],
        chooseSystemMenuList: []
      },
      menuType: 'wechat',
      wechatMenuList: [], // 营销平台菜单
      corpMenuList: [], // 企微平台菜单
      systemMenuList: [], // 运维平台菜单
      ruleForm1: {
        roleName: null,
        roleId: '',
        delEmpIds: [],
        roleGroupId: '',
        currentMenuList: []
      },
      delRoleStaffIds: [],
      // 账号列表
      totalR: 0,
      pageR: 1,
      pageSizeR: 8,
      defaultProps2: {
        children: 'children',
        label: 'menuName'
      },
      roleTreeData: [],
      currentRoleStaff: [],
      roleId: '',
      currentRoleInfo: {},
      // 以下是添加部门相关
      addDeptFormVisible: false,
      addDept: {
        deptParentIds: null,
        deptName: null,
        parentId: null,
        deptDesc: ''
      },
      addDeptRules: {
        deptName: [{ required: true, min: 2, max: 64, message: '必填,支持2~64个字符', trigger: 'blur' }],
        deptParentIds: [{ required: true, message: '必选', trigger: 'blur' }]
      },
      editRoleGroupModal: false,
      editingRoleGroup: {
        roleGroupId: '',
        roleName: '',
        roleGroupCode: ''
      },
      // 获取角色下账号列表相关
      tenantList: [],
      searchInfo: {
        roleInputValue: '',
        tenantId: ''
      },
      tableHeight2: '200px',
      isExport: false, // 导出防抖
      // 添加编辑账户相关
      isEditAccount: false,
      mode: 'create',
      posOptions: [], // 角色列表
      // empList: [], // 员工列表
      accountData: {
        accountId: '',
        name: '',
        account: '',
        password: '',
        passwords: '',
        email: '',
        posOption: []
        // userId: ''
      },
      newAccount: {
        name: '',
        account: '',
        password: '',
        passwords: '',
        email: '',
        posOption: []
        // userId: ''
      },
      addRules: {
        name: [{ required: true, min: 2, max: 64, message: '必填,支持2~64个字符', trigger: 'blur' }],
        password: [{ required: true, min: 6, max: 64, message: '必填,支持6~64个字符', trigger: 'blur' }],
        passwords: [{ required: true, min: 6, max: 64, message: '必填,支持6~64个字符', trigger: 'blur' }],
        account: [{ required: true, validator: checkTel, message: '必填,请输入正确的手机号', trigger: 'blur' }],
        email: [{required: true, validator: validateEmail, trigger: 'blur'}],
        posOption: [{ required: true, message: '必填,请选择角色', trigger: 'change', type: 'array' }]
        // userId: [{ required: true, message: '必填,请选择员工', trigger: ['blur', 'change'] }]
      },
      editRules: {
        name: [{ required: true, min: 2, max: 64, message: '必填,支持2~64个字符', trigger: 'blur' }],
        password: [{ min: 6, max: 64, message: '支持6~64个字符', trigger: 'blur' }],
        passwords: [{ min: 6, max: 64, message: '支持6~64个字符', trigger: 'blur' }],
        account: [{ required: true, validator: checkTel, message: '必填,请输入正确的手机号', trigger: 'blur' }],
        email: [{required: true, validator: validateEmail, trigger: 'blur'}],
        posOption: [{ required: true, message: '必填,请选择角色', trigger: 'change', type: 'array' }]
        // userId: [{ required: true, message: '必填,请选择员工', trigger: ['blur', 'change'] }]
      },
      // 给某个角色添加成员相关
      isShowAddMeber: false,
      searchInfo2: {
        name: '',
        tenantId: ''
      },
      pageUser: 1,
      pageSizeUser: 10,
      countUser: 0,
      accountList: [],
      selectAccountList: []
    }
  },
  methods: {
    // 给某个角色添加成员
    showAddMember () {
      this.isShowAddMeber = true
      this.pageUser = 1
      this.accountList = []
      this.getAccountList()
    },
    // 获取角色下不存在的账号列表
    getAccountList () {
      let params = {
        roleId: this.roleId,
        isBind: false,
        name: this.searchInfo2.name || null,
        tenantId: this.searchInfo2.tenantId,
        currentPage: this.pageUser,
        pageSize: this.pageSizeUser
      }
      let url = `${this.SERVICE_TENANT}/account/role/accounts`
      this.get(url, params).then(res => {
        if (res.data.code === 200) {
          let data = res.data.data
          if (data && data.list && data.list.length) {
            this.countUser = +data.total
            this.accountList = data.list
          } else {
            this.accountList = []
          }
        }
      }).catch(e => {
        this.handleError(e)
      })
    },
    handleUserSearch () {
      this.pageUser = 1
      this.getAccountList()
    },
    handleSizeUserChange (val) {
      this.pageUser = 1
      this.pageSizeUser = val
      this.getAccountList()
    },
    handleCurrentUserChange (val) {
      this.pageUser = val
      this.getAccountList()
    },
    // 选择成员
    handleSelectionChange (val) {
      this.selectAccountList = val
    },
    // 保存给角色添加成员
    saveAddMember () {
      let accountIds = this.selectAccountList.map(item => item.accountId)
      if (!accountIds || !accountIds.length) {
        return this.showWarning('至少选择一个成员')
      }
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      let url = `${this.SERVICE_TENANT}/account/role/${this.roleId}/add`
      this.posts(url, accountIds).then(res => {
        this.isLoading = false
        if (res.data.code === 200) {
          this.showSucc(res.data.message)
          this.getcurrentRoleStaffList()
          this.isShowAddMeber = false
        }
      }).catch(err => {
        this.isLoading = false
        this.handleError(err)
      })
    },
    // 重置添加成员
    resetMember () {
      this.searchInfo2.name = ''
      this.searchInfo2.tenantId = this.tenantList[0] ? this.tenantList[0].tenantId : null
      this.pageUser = 1
      this.accountList = []
      this.$refs.accountListRef.clearSelection()
    },
    // 导出
    // exportFile () {
    //   if (this.isExport) {
    //     return
    //   }
    //   this.isExport = true
    //   let url = ``
    //   let link = document.createElement('a')
    //   let params = {}
    //   params.roleId = this.roleId
    //   this.post(url, params, {responseType: 'blob'}).then(res => {
    //     this.isExport = false
    //     if (res.data.type === 'application/json') {
    //       return this.showErrMsg('权限不足')
    //     }
    //     let disposition = res.headers['content-disposition'] && res.headers['content-disposition'].split('=')[1]
    //     let fileName = decodeURI(disposition)
    //     let blob = new Blob([res.data])
    //     let url = window.URL.createObjectURL(blob)
    //     link.href = url
    //     link.download = fileName // 自定义文件名
    //     link.click() // 下载文件
    //     URL.revokeObjectURL(url) // 释放内存
    //   }).catch(err => {
    //     this.handleError(err)
    //     this.isExport = false
    //   })
    // },
    // 显示编辑角色组弹框
    editRoleGroup (data) {
      this.editingRoleGroup.roleGroupId = data.roleGroupId
      this.editingRoleGroup.roleName = data.roleName
      this.editingRoleGroup.roleGroupCode = data.roleGroupCode
      this.editRoleGroupModal = true
    },
    // 添加角色组校验
    addRoleGroupSaveBtn () {
      if (!this.addRoleGroup.addRoleGroupName) {
        this.$message({
          message: '请填写角色组名称',
          type: 'warning'
        })
      } else {
        this.addRoleGroupSave()
      }
    },
    // 添加角色组
    addRoleGroupSave () {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      let url = `${this.SERVICE_ROLE}/group/add`
      let param = {
        roleGroupName: this.addRoleGroup.addRoleGroupName
      }
      this.post(url, param).then(res => {
        this.isLoading = false
        if (res.data.code === 200) {
          this.showSucc('添加成功！')
          this.addRoleGroup.addRoleGroupName = ''
          this.addRoleGroupModal = false
          this.init()
        }
      }).catch(e => {
        this.isLoading = false
        this.handleError(e)
      })
    },
    // 重置添加角色组的表单
    clearAddRoleFields () {
      this.$refs.addRoleGroup.resetFields()
      this.addRoleGroup = {
        addRoleGroupName: null
      }
    },
    // 编辑角色组
    editRoleGroupSaveBtn () {
      if (!this.editingRoleGroup.roleName) {
        this.$message({
          message: '请填写角色组名称',
          type: 'warning'
        })
      } else {
        this.editRoleGroupSave()
      }
    },
    // 保存编辑角色组
    editRoleGroupSave () {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      let url = `${this.SERVICE_ROLE}/group/update`
      let param = {
        roleGroupId: this.editingRoleGroup.roleGroupId,
        roleGroupName: this.editingRoleGroup.roleName
      }
      this.post(url, param).then(res => {
        this.isLoading = false
        if (res.data.code === 200) {
          this.showSucc('修改成功！')
          this.initRoleGroupDialog()
          this.init()
        }
      }).catch(e => {
        this.isLoading = false
        this.handleError(e)
      })
    },
    // 重置编辑角色组的表单
    initRoleGroupDialog () {
      this.$refs.editingRoleGroup.resetFields()
      this.editRoleGroupModal = false
      setTimeout(() => {
        this.editingRoleGroup = {
          roleGroupId: '',
          roleName: '',
          roleGroupCode: ''
        }
      }, 500)
    },
    // 删除角色组
    delRoleGroupBtn () {
      this.$confirm('此操作将永久删除该角色组，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.ensureDelRoleGroup()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 确认删除角色组
    ensureDelRoleGroup () {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      let url = `${this.SERVICE_ROLE}/group/del`
      let param = {
        roleGroupId: this.editingRoleGroup.roleGroupId
      }
      this.post(url, param).then(res => {
        this.isLoading = false
        if (res.data.code === 200) {
          this.showSucc('删除成功！')
          this.initRoleGroupDialog()
          this.init()
        }
      }).catch(e => {
        this.isLoading = false
        this.showErrMsg(e.data.message)
      })
    },
    // 添加、编辑角色校验
    addRoleSaveBtn () {
      this.$refs.addRole.validate((valid) => {
        if (valid) {
          if (!this.banFlag) {
            this.addRoleSave()
          } else {
            this.updateRole()
          }
        }
      })
    },
    // 添加、编辑角色蒙层
    addRoleBtn (val) {
      this.addRoleModal = true
      if (val === 0) {
        this.banEdit = false
        this.banFlag = false
        this.roleModalText = '添加角色'
        this.addRole = {
          addRoleName: null,
          roleGroupId: null,
          parentRoleId: null,
          // menuList: []
          chooseWechatMenuList: [],
          chooseCorpMenuList: [],
          chooseSystemMenuList: []
        }
        // 初始化上级角色选择列表
        this.roleGroupRoleList = []
        this.roleGroupRoleList.push({roleId: '000', roleName: '请先选择分组'})
      } else if (val === 1) {
        this.banEdit = false
        this.banFlag = true
        this.roleModalText = '编辑角色'
        this.getRoleMenu()
      } else if (val === 2) {
        this.banEdit = true
        this.roleModalText = '查看角色'
        this.getRoleMenu()
      }
    },
    // 获取当前角色的菜单
    getRoleMenu () {
      let url = `${this.SERVICE_ROLE}/menu/v2?roleId=${this.roleId}`
      this.get(url).then(rsp => {
        if (rsp.data.code === 200) {
          let data = rsp.data.data
          this.addRole.addRoleName = this.currentRoleInfo.roleName
          this.addRole.roleGroupId = this.currentRoleInfo.roleGroupId
          this.addRole.roleId = this.currentRoleInfo.roleId
          this.getCurrentRoleGroupIdFn(this.currentRoleInfo.roleGroupId)
          this.addRole.parentRoleId = this.currentRoleInfo.parentId
          // 对菜单进行分组：营销平台、企微平台、运维平台
          let chooseWechatMenuList = []
          let chooseCorpMenuList = []
          let chooseSystemMenuList = []
          data.forEach(menuInfo => {
            // 营销平台
            if (menuInfo.platform === 'customer_console') {
              chooseWechatMenuList = chooseWechatMenuList.concat(this.getSelectedListFromTree(menuInfo))
            // 企微平台
            } else if (menuInfo.platform === 'wecom_console') {
              chooseCorpMenuList = chooseCorpMenuList.concat(this.getSelectedListFromTree(menuInfo))
            // 运维平台
            } else if (menuInfo.platform === 'admin_console') {
              chooseSystemMenuList = chooseSystemMenuList.concat(this.getSelectedListFromTree(menuInfo))
            }
          })
          this.addRole.chooseWechatMenuList = chooseWechatMenuList
          this.addRole.chooseCorpMenuList = chooseCorpMenuList
          this.addRole.chooseSystemMenuList = chooseSystemMenuList
          console.log('=== getRoleMenu addRole ===: ', this.addRole)
          // 回显菜单
          this.$nextTick(() => {
            this.handleMenuCheck(this.addRole.chooseWechatMenuList, 'wechatTreeRef')
            this.handleMenuCheck(this.addRole.chooseCorpMenuList, 'corpTreeRef')
            this.handleMenuCheck(this.addRole.chooseSystemMenuList, 'systemTreeRef')
          })
        }
      }).catch(e => {
        this.handleError(e)
      })
    },
    // 将树状结构的数据全部展开成一级数组结构, 并返回被选中的数据
    getSelectedListFromTree (tree) {
      // console.log('=== getSelectedListFromTree tree ===: ')
      let arr = []
      if (tree.isSelected) {
        arr.push(tree)
        if (tree.children && tree.children[0]) {
          tree.children.forEach(item => {
            let stepArr = this.getSelectedListFromTree(item)
            arr = arr.concat(stepArr)
          })
        }
      }
      return arr
    },
    // 更新角色信息
    updateRole () {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      let menus = this.addRole.chooseWechatMenuList.concat(this.addRole.chooseCorpMenuList, this.addRole.chooseSystemMenuList)
      // let menuIds = this.addRole.chooseWechatMenuList.concat(this.addRole.chooseCorpMenuList, this.addRole.chooseSystemMenuList)
      // 从中区分导航和菜单，并获取它们的menuId
      let navMenuIds = [] // 导航id
      let menuIds = [] // 菜单id
      menus.forEach(menu => {
        if (menu.isNav) {
          navMenuIds.push(menu.menuId)
        } else {
          menuIds.push(menu.menuId)
        }
      })
      console.log('addRoleSave navMenuIds: ', navMenuIds)
      console.log('addRoleSave menuIds: ', menuIds)
      let param = {
        roleName: this.addRole.addRoleName,
        roleId: this.addRole.roleId,
        roleGroupId: this.addRole.roleGroupId,
        parentId: this.addRole.parentRoleId || -1,
        menuIds: menuIds,
        navMenuIds: navMenuIds
      }
      let url = `${this.SERVICE_ROLE}/update`
      this.posts(url, param).then(res => {
        this.isLoading = false
        if (res.data.code === 200) {
          this.currentRoleInfo.roleName = this.addRole.addRoleName
          this.addRoleModal = false
          this.addRole = {
            addRoleName: null,
            roleGroupId: null,
            parentRoleId: null,
            // menuList: []
            chooseWechatMenuList: [],
            chooseCorpMenuList: [],
            chooseSystemMenuList: []
          }
          this.showSucc('修改成功！')
          this.init()
        }
      }).catch(e => {
        this.isLoading = false
        this.handleError(e)
      })
    },
    // 添加角色信息
    addRoleSave () {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      let menus = this.addRole.chooseWechatMenuList.concat(this.addRole.chooseCorpMenuList, this.addRole.chooseSystemMenuList)
      // 从中区分导航和菜单，并获取它们的menuId
      let navMenuIds = [] // 导航id
      let menuIds = [] // 菜单id
      menus.forEach(menu => {
        if (menu.isNav) {
          navMenuIds.push(menu.menuId)
        } else {
          menuIds.push(menu.menuId)
        }
      })
      // console.log('addRoleSave navMenuIds: ', navMenuIds)
      // console.log('addRoleSave menuIds: ', menuIds)
      let url = `${this.SERVICE_ROLE}/add`
      let param = {
        roleName: this.addRole.addRoleName,
        roleGroupId: this.addRole.roleGroupId,
        parentId: -1,
        menuIds: menuIds,
        navMenuIds: navMenuIds
      }
      this.posts(url, param).then(res => {
        this.isLoading = false
        if (res.data.code === 200) {
          this.showSucc('添加成功！')
          this.addRoleModal = false
          this.addRole = {
            addRoleName: null,
            roleGroupId: null,
            parentRoleId: null,
            // menuList: []
            chooseWechatMenuList: [],
            chooseCorpMenuList: [],
            chooseSystemMenuList: []
          }
          this.init()
        }
      }).catch(e => {
        this.isLoading = false
        this.handleError(e)
      })
    },
    // 删除角色校验
    delRoleBtn () {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.ensureDelRole()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 确认删除角色
    ensureDelRole () {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      let param = {
        roleId: this.currentRoleInfo.roleId
      }
      let url = `${this.SERVICE_ROLE}/del`
      this.post(url, param).then(res => {
        this.isLoading = false
        if (res.data.code === 200) {
          this.roleGroupList = []
          this.addRoleModal = false
          this.showSucc('移除成功！')
          this.init()
          this.currentRoleInfo = {}
        }
      }).catch(e => {
        this.isLoading = false
        this.handleError(e)
      })
    },
    // 添加编辑角色(营销平台菜单选择)
    checkWechatMenuList (data, selected) {
      this.handleMenuData(selected, this.addRole, 'chooseWechatMenuList')
    },
    // 添加编辑角色(企微平台菜单选择)
    checkCorpMenuList (data, selected) {
      this.handleMenuData(selected, this.addRole, 'chooseCorpMenuList')
    },
    // 添加编辑角色(运维平台菜单选择)
    checkSystemMenuList (data, selected) {
      this.handleMenuData(selected, this.addRole, 'chooseSystemMenuList')
    },
    // 添加、编辑角色重置表单
    resetEmployeeInfo () {
      this.menuType = 'wechat'
      this.addRole.chooseWechatMenuList = []
      this.addRole.chooseCorpMenuList = []
      this.addRole.chooseSystemMenuList = []
    },
    // 批量删除账号
    selectDel () {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      this.$confirm('是否确定删除选择的账号?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = `${this.SERVICE_TENANT}/account/invalid`
        let accountIds = this.delRoleStaffIds
        this.posts(url, accountIds).then(res => {
          this.isLoading = false
          if (res.data.code === 200) {
            this.showSucc(res.data.message)
            this.getcurrentRoleStaffList()
          }
        }).catch(e => {
          this.isLoading = false
          this.handleError(e)
        })
      }).catch(() => {
        this.isLoading = false
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 从当前角色批量移除人员
    selectRemove () {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      this.$confirm('是否确定移除选择的人员?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = `${this.SERVICE_TENANT}/account/role/${this.roleId}/remove`
        let accountIds = this.delRoleStaffIds
        this.posts(url, accountIds).then(res => {
          this.isLoading = false
          if (res.data.code === 200) {
            this.showSucc(res.data.message)
            this.getcurrentRoleStaffList()
          }
        }).catch(e => {
          this.isLoading = false
          this.handleError(e)
        })
      }).catch(() => {
        this.isLoading = false
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 选择（账号列表）
    selectionChange (selection) {
      this.delRoleStaffIds = selection.map(val => {
        return val.accountId
      })
    },
    // 切换角色
    openRoleDetails (data) {
      if (!data.roleId) return
      this.menuModal = true
      this.roleId = data.roleId
      this.currentRoleInfo = data
      this.pageR = 1
      this.getcurrentRoleStaffList()
    },
    // 获取当前角色下的账号列表
    getcurrentRoleStaffList () {
      let param = {
        roleId: this.roleId,
        isBind: true,
        name: this.searchInfo.roleInputValue || null,
        tenantId: this.searchInfo.tenantId || null,
        currentPage: this.pageR,
        pageSize: this.pageSizeR
      }
      let url = `${this.SERVICE_TENANT}/account/role/accounts`
      this.get(url, param).then(res => {
        this.loading = false
        if (res.data.code === 200) {
          let data = res.data.data
          if (data && data.list && data.list.length) {
            this.totalR = Number(data.total)
            this.currentRoleStaff = data.list
          } else {
            this.totalR = 0
            this.currentRoleStaff = []
          }
          this.tableHeight2 = this.currentRoleStaff && this.currentRoleStaff.length ? (this.currentRoleStaff.length + 1) * 50 + 3 + 'px' : '200px'
        }
      }).catch(e => {
        this.handleError(e)
      })
    },
    // 名称搜索（账号列表）
    handleRoleSearch () {
      this.pageR = 1
      this.getcurrentRoleStaffList()
    },
    // 页码变化（账号列表）
    handleCurrentChangeR (val) {
      this.pageR = val
      this.getcurrentRoleStaffList()
    },
    // 显示添加账号
    // startAddUser () {
    //   this.mode = 'create'
    //   this.isEditAccount = true
    //   this.getEmpList()
    // },
    // 编辑账号
    handleEdit (account) {
      this.mode = 'edit'
      this.getUserDetail(account)
      // this.getEmpList(account.userId)
    },
    // 获取账户详情
    getUserDetail (account) {
      let url = `${this.SERVICE_TENANT}/account/${account.accountId}`
      this.get(url).then(res => {
        if (res.data.code === 200) {
          let data = res.data.data
          if (data) {
            this.assignKey(this.accountData, data)
            let posOption = data.roles.map(info => {
              return info.roleId
            })
            this.accountData.posOption = posOption
            this.accountData.password = ''
            this.accountData.passwords = ''
            this.isEditAccount = true
          }
        }
      }).catch(e => {
        this.handleError(e)
      })
    },
    // 删除账号
    handleDelete (info) {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      this.$confirm('确认删除该账户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = `${this.SERVICE_TENANT}/account/invalid/${info.accountId}`
        this.posts(url).then(res => {
          this.isLoading = false
          if (res.data.code === 200) {
            this.showSucc(res.data.message)
            this.getcurrentRoleStaffList()
          }
        }).catch(e => {
          this.isLoading = false
          this.handleError(e)
        })
      }).catch(e => {
        this.isLoading = false
        this.$message({
          type: 'info',
          message: '操作已取消'
        })
      })
    },
    // 从当前角色移除当前人员
    handleRemove (info) {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      this.$confirm('确认移除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = `${this.SERVICE_TENANT}/account/role/${this.roleId}/remove`
        let accountIds = [info.accountId]
        this.posts(url, accountIds).then(res => {
          this.isLoading = false
          if (res.data.code === 200) {
            this.showSucc(res.data.message)
            this.getcurrentRoleStaffList()
          }
        }).catch(e => {
          this.isLoading = false
          this.handleError(e)
        })
      }).catch(e => {
        this.isLoading = false
        this.$message({
          type: 'info',
          message: '操作已取消'
        })
      })
    },
    // 提交（添加编辑账号）
    saveAccount () {
      // // 添加账户
      // if (this.mode === 'create') {
      //   this.$refs.addStaff.validate((valid) => {
      //     if (valid) {
      //       if (this.isLoading) {
      //         return
      //       }
      //       this.isLoading = true
      //       // 判断密码是否相同
      //       if (this.newAccount.password !== this.newAccount.passwords) {
      //         this.isLoading = false
      //         return this.$message({
      //           message: '两次输入的密码不一致！',
      //           type: 'warning'
      //         })
      //       }
      //       let url = `${this.SERVICE_TENANT}/account/add`
      //       let param = {
      //         account: this.newAccount.account,
      //         password: this.newAccount.password,
      //         roleIds: this.newAccount.posOption,
      //         userId: this.newAccount.userId
      //       }
      //       this.posts(url, param).then(res => {
      //         this.isLoading = false
      //         if (res.data.code === 200) {
      //           this.showSucc(res.data.message)
      //           this.isEditAccount = false
      //           this.getcurrentRoleStaffList()
      //         }
      //       }).catch(e => {
      //         this.isLoading = false
      //         this.handleError(e)
      //       })
      //     }
      //   })
      // // 编辑账户
      // } else if (this.mode === 'edit') {
      //   this.$refs.editStaff.validate((valid) => {
      //     if (valid) {
      //       if (this.isLoading) {
      //         return
      //       }
      //       this.isLoading = true
      //       // 如果填写了密码，则判断密码是否相同
      //       if ((this.accountData.password || this.accountData.passwords) && this.accountData.password !== this.accountData.passwords) {
      //         this.isLoading = false
      //         return this.$message({
      //           message: '两次输入的密码不一致！',
      //           type: 'warning'
      //         })
      //       }
      //       let url = `${this.SERVICE_TENANT}/account/${this.accountData.accountId}`
      //       let param = {
      //         accountId: this.accountData.accountId,
      //         account: this.accountData.account,
      //         password: this.accountData.password || null,
      //         roleIds: this.accountData.posOption,
      //         userId: this.accountData.userId
      //       }
      //       this.posts(url, param).then(res => {
      //         this.isLoading = false
      //         if (res.data.code === 200) {
      //           this.showSucc(res.data.message)
      //           this.isEditAccount = false
      //           this.getcurrentRoleStaffList()
      //         }
      //       }).catch(e => {
      //         this.isLoading = false
      //         this.handleError(e)
      //       })
      //     }
      //   })
      // }
    },
    // 关闭添加编辑账号时 表单置空
    clearAddUserFields () {
      this.$refs.addStaff && this.$refs.addStaff.resetFields()
      this.$refs.editStaff && this.$refs.editStaff.resetFields()
      this.newAccount = {
        name: '',
        account: '',
        password: '',
        passwords: '',
        email: '',
        posOption: []
      }
      this.accountData = {
        accountId: '',
        name: '',
        account: '',
        password: '',
        passwords: '',
        email: '',
        posOption: []
      }
    },
    // 获取所有角色组信息
    fetchRoleGroupAll () {
      return new Promise((resolve, reject) => {
        let url = `${this.SERVICE_ROLE}/group`
        this.get(url).then(res => {
          if (res.data.code === 200) {
            let data = res.data.data
            resolve(data)
          } else {
            reject(res)
          }
        }).catch(e => {
          reject(e)
        })
      })
    },
    // 获取员工选项
    // getEmpList (userId) {
    //   let url = `/org/emp/list`
    //   let params = {}
    //   if (userId) {
    //     params.userId = userId
    //   }
    //   this.get(url, params).then(res => {
    //     if (res.data.code === 200) {
    //       let data = res.data.data
    //       if (data && data.list && data.list.length) {
    //         this.empList = data.list
    //       } else {
    //         this.empList = []
    //       }
    //     }
    //   }).catch(err => {
    //     this.handleError(err)
    //   })
    // },
    // 获取所有菜单列表
    getTenantMenuList () {
      let url = `${this.SERVICE_ROLE}/menu/v2`
      this.get(url).then(res => {
        this.loading = false
        if (res.data.code === 200) {
          let menuList = res.data.data
          if (menuList && menuList.length) {
            // 对菜单进行分组：营销平台、企微平台、运维平台
            let wechatMenuList = [] // 营销平台菜单
            let corpMenuList = [] // 企微平台菜单
            let systemMenuList = [] // 运维平台菜单
            menuList.forEach(menuInfo => {
              // 营销平台
              if (menuInfo.platform === 'customer_console') {
                wechatMenuList.push(menuInfo)
              // 企微平台
              } else if (menuInfo.platform === 'wecom_console') {
                corpMenuList.push(menuInfo)
              // 运维平台
              } else if (menuInfo.platform === 'admin_console') {
                systemMenuList.push(menuInfo)
              }
            })
            this.wechatMenuList = wechatMenuList
            this.corpMenuList = corpMenuList
            this.systemMenuList = systemMenuList
          }
        }
      }).catch(e => {
        this.loading = false
        this.handleError(e)
      })
    },
    // 菜单列表数据处理
    handleData (val) {
      if (val === 0) return
      val.forEach(item => {
        this.roleGroupRoleList.push(item)
        if (item.children.length) {
          this.handleData(item.children)
        }
      })
    },
    // 角色列表数据处理
    filterRole (tree, filters) {
      let result = []
      tree.forEach(ele => {
        let isMatched = filters.filter(item => item === ele.roleCode)[0]
        if (!isMatched) {
          var stepRes = {}
          for (let key of Object.keys(ele)) {
            if (key !== 'children') {
              stepRes[key] = ele[key]
            }
          }
          if (ele.children && ele.children.length > 0) {
            stepRes.children = this.filterRole(ele.children, filters)
          }
          result.push(stepRes)
        }
      })
      return result
    },
    // 角色列表数据处理
    unitRoles (list) {
      list.forEach((ele, index) => {
        if (ele.roleId) {
          this.posOptions.push({roleId: ele.roleId, roleName: ele.roleName})
        }
        if (ele.children && ele.children.length > 0) {
          this.unitRoles(ele.children)
        }
      })
      return list
    },
    // 角色列表数据处理
    handleTreeUnique (list) {
      list.forEach((ele, index) => {
        ele.listId = ele.createTime + index + ele.deptId
        if (ele.children.length > 0) {
          this.handleTreeUnique(ele.children)
        }
      })
      return list
    },
    // 处理数据（当前角色的菜单）
    getCurrentRoleGroupIdFn (value) {
      this.addRole.parentRoleId = null
      this.roleGroupRoleList = []
      this.roleGroupRoleList.push({roleId: '-1', roleName: '顶级角色'})
      this.roleGroupList.forEach(ele => {
        if (ele.roleGroupId === value) {
          if (ele.children) {
            this.handleData(ele.children)
          }
        }
      })
    },
    // 关闭抽屉
    beforeClose (name) {
      this[name] = false
    },
    // 获取租户列表
    fetchTenantList () {
      return new Promise((resolve, reject) => {
        let url = `${this.SERVICE_TENANT}/search`
        this.get(url).then(res => {
          if (res.data.code === 200) {
            let data = res.data.data
            resolve(data)
          } else {
            reject(res)
          }
        }).catch(e => {
          reject(e)
        })
      })
    },
    /**
     * 点击选中菜单，将menuId进行存储
     * @param {Object} selected 用于获取选中的node的key值和获取半选中的node的key值
     * @param {Object} obj 需要修改的目标
     * @param {String} chooseListName 目标中的key
     */
    handleMenuData (selected, obj, chooseListName) {
      // 获取选中的node (完全选中状态)
      let checkedNodes = selected.checkedNodes || []
      // console.log('=== checkedNodes ===: ', checkedNodes)
      // 获取半选中的node（半选中状态）
      let halfCheckedNodes = selected.halfCheckedNodes || []
      // console.log('=== halfCheckedNodes ===: ', halfCheckedNodes)
      let menuList = []
      if (checkedNodes && halfCheckedNodes.length) {
        menuList = checkedNodes.concat(halfCheckedNodes)
      } else {
        menuList = checkedNodes
      }
      obj[chooseListName] = menuList
      // console.log('==== obj ===: ', obj)
      this.$forceUpdate()
    },
    /**
     * 接口获取menuId数据，菜单tree回显
     * @param {Array} menuList 包含全选和半选的menu
     * @param {String} treeRefName 元素对应的ref名称
     */
    handleMenuCheck (menuList, treeRefName) {
      // 实际选中的菜单id
      let checkedKeys = []
      // menuList是设置选中的数据
      menuList.forEach(i => {
        let menuId = i.menuId
        // 根据id 拿到 Tree 组件中的node的所有信息
        let node = this.$refs[treeRefName].getNode(menuId)
        // node.isLeaf：判断当前节点是否为子节点
        if (node && node.isLeaf) {
          // 如果是子节点，就添加对应菜单id
          checkedKeys.push(menuId)
        }
      })
      // 设置选中
      this.$refs[treeRefName].setCheckedKeys(checkedKeys)
    },
    init () {
      Promise.all([this.fetchRoleGroupAll(), this.fetchTenantList()]).then(res => {
        if (res) {
          let data1 = res[0]
          let data2 = res[1]
          if (data1 && data1.length) {
            let arr = JSON.parse(JSON.stringify(data1))
            this.roleGroupList = arr
            this.posOptions = []
            this.unitRoles(arr)
            let tempData = data1
            for (var i in tempData) {
              for (var j in tempData[i]) {
                if (j === 'roleGroupName') {
                  tempData[i]['roleName'] = tempData[i][j]// 修改属性名为“title”
                  delete tempData[i]['roleGroupName']// 删除“name”
                }
              }
            }
            tempData = this.handleTreeUnique(tempData)
            this.roleTreeData = this.filterRole(tempData, [])
            if (!this.currentRoleInfo.roleId) {
              this.roleId = data1[0].children && data1[0].children.length > 0 ? data1[0].children[0].roleId : ''
              this.currentRoleInfo = data1[0].children && data1[0].children.length > 0 ? data1[0].children[0] : { roleId: '', roleName: '' }
            }
          }
          if (data2 && data2.length) {
            this.tenantList = data2
            // // 默认选中第一个租户
            // this.searchInfo.tenantId = this.tenantList[0].tenantId
            // this.searchInfo2.tenantId = this.tenantList[0].tenantId
          } else {
            this.tenantList = []
            // this.searchInfo.tenantId = null
            // this.searchInfo2.tenantId = null
          }
          this.getcurrentRoleStaffList()
        } else {
          this.getcurrentRoleStaffList()
        }
      }).catch(err => {
        this.handleError(err)
      })
    }
  },
  created () {
    this.init()
    // this.getEmpList()
    this.getTenantMenuList()
  }
}
</script>
<style lang="stylus" scoped>
.roles-wrapper
  width 100%
  height 100%
  .roles-body
    display flex
    width 100%
    height 100%
    font-size 12px
    overflow-y auto
    background #f2f2f6
    padded_box(border-box, 6px)
    border-radius 6px
    .tab-wrapper
      display flex
      align-items center
      margin-bottom 14px
      padded_box(border-box, 0 30px)
      width 100%
      height 64px
      wrapper()
    .tabsBox
      min-width 160px
      padding 15px 10px
      background #fff
      border-radius 6px 0 0 6px
      border-right 2px solid #f2f2f6
      .treeBoxS >>> .el-tree-node
        margin 6px 0 !important
      .roleFn
        display flex
        padding-bottom 19px
        justify-content center
        padding-top 2px
        padding-bottom 10px
      .roleBtn
        border 1px solid #c3c3c3
        border-radius 14px
        cursor pointer
        color: #606266
        padding 5px 12px
        font-size 12px
        background #fff
        &:first-child
          margin-right 10px
    .sTabsBox >>> .el-tabs__header
      width 160px !important
    .sTabsBox >>> .el-tabs__nav-scroll
      width 160px !important
    .sTabsBox >>> .el-tree-node__content
      height 24px !important
    .sTabsBox >>> .el-tree-node
      margin 6px 0
    .depts-cont, .role-cont
      // scroll()
      width calc(100% - 40px)
      height calc(100% - 70px)
      background #f2f2f6
      padding 6px
      box-sizing border-box
      margin 10px 20px 20px
      border-radius 6px
      .handle
        width 100%
        background #fff
        border-radius 6px
        padding 15px 20px
        box-sizing border-box
        margin-bottom 6px
        display flex
        justify-content space-between
        align-items center
        .handle-left
          display flex
          align-items center
        .handle-right
          display flex
          align-items center
          .search-input-box,.search-select-box
            width 160px
            height 30px
          .search-btn
            color #3496FF
            cursor pointer
            font-size 12px
        >>> button.el-button--primary.is-disabled
          color: #c0c4cc;
          cursor: not-allowed;
          background-image: none;
          background-color: #fff;
          border-color: #ebeef5;
        >>> button.btn
            // color: #3496FF;
            display block
            float left
            margin-left 0
            margin-right 20px
            height: 30px;
            line-height: 1px
        >>> .import,.addBtn,.invite
          color #3496FF
          background-color #fff
          border 1px solid #3496FF
        >>> button.approve
          border none
        >>> .import:hover,.addBtn:hover,.invite:hover
          color #fff
          background-color #3496FF
        >>> .del
          color #FA376C
          background-color #fff
          border 1px solid #FA376C
        >>> .del:hover
          color #fff
          background-color #f56c6c
      .depts-table, .role-table
        scroll()
        width 100%
        height calc(100% - 66px)
        padding 15px 20px
        box-sizing border-box
        background #fff
        border-radius 6px
        position relative
        .table-wrapper
          height 100%
          width 100%
          scroll()
          .handleBtn
            display inline
            cursor pointer
            color #3496ff
            margin-right 15px
    .custom-tree-node
      display flex
      justify-content space-between
      width 100%
      align-items center
      margin 5px 0
      // font-size 15px
      .icon
        margin-right 10px
      .iconfont
        font-size 16px
      .editIcon
        color rgb(189, 189, 189)
        &:hover
          color #606266
      img
        width 18px
        heiht 18px
      .custom-tree-node.active
        color #449EFE
        font-weight 600
      >>> .el-tree-node
        margin 10px 0
    .el-tree.roleTree
      >>>.el-tree-node__content
        height 35px
    .rightPart
      >>> .el-checkbox__inner:hover
        border 1px solid #15c78a
        border-color #15c78a
      >>> .el-checkbox__input.is-checked .el-checkbox__inner, .el-checkbox__input.is-indeterminate .el-checkbox__inner
        background-color #15c78a
        border-color #15c78a
      >>> .el-checkbox__input.is-focus .el-checkbox__inner
        border 1px solid #15c78a
      >>> .el-checkbox__input.is-indeterminate .el-checkbox__inner
        background-color #15c78a
        border-color #15c78a
    .role
      .title
        // font-size 18px
        padding-bottom 17px
      .downTitle
        // font-size 17px
        padding-bottom 15px
        padding-left 20px
    .depts,.role
      height 100%
      // padding: 70px 28px 0 24px
      -webkit-box-shadow: none!important
      box-shadow: none!important
      // padding-bottom: 80px!important
      position relative
      background #fff
      .title
        // font-size 18px
      .downTitle
        // font-size 17px
        padding-bottom 15px
        padding-left 20px
      .search-wrapper
        display flex
        .search-item
          display flex
          align-items center
          .item-name
            margin 0 15px 0 30px
            min-width 60px
            text-align right
          .name-else
            margin 0 15px 0 0
            min-width 45px
        .search-btn
          margin 0 15px 0 60px
      .add-btn
        margin 20px 0 10px
      .status-wrapper
        display flex
        align-items center
    >>>.el-tabs__nav-scroll
      width 305px
      border 1px solid #3496FF
      box-sizing border-box
      border-radius 20px
    >>>.el-tabs__nav-wrap
      margin-bottom none
    >>>.el-tabs--border-card>.el-tabs__content
      // height calc(100% - 20px)
      padding 0
      // margin-top 10px
      // border 1px solid #dcdee2
      // -webkit-box-shadow: 0px 3px 10px rgba(0,0,0,0.1);
      // box-shadow: 0px 3px 10px rgba(0,0,0,0.1);
    >>>.tabs.el-tabs.el-tabs--top
      height 100%
      // border 1px solid #dcdee2
      -webkit-box-shadow: none!important
      box-shadow: none!important
      padding: 0!important
      border none
    >>>.el-tabs__header.is-top
      width 306px
      margin 0 auto 10px
      background-color #fff
      box-sizing border-box
      border none
    >>>.el-tabs__item.is-top.is-active
      color #fff!important
      background-color #3496FF
    // >>>.el-tabs__content
    //   border: 1px solid #dcdee2;
    >>>.el-tabs__nav-scroll
      display flex
      justify-content center
      #tab-first,#tab-second
        color #3496FF
        padding 0
        width 51%
        line-height 30px
        height 29px
        text-align center
    >>>.el-tabs--card>.el-tabs__header .el-tabs__item
      border none
    >>>.el-tabs__nav.is-top
      // padding 3px 43px
      width 100%
      border none
      .el-tabs__item
        color none
    .rightPart
      width 0
      flex 1
      border-radius 0 6px 6px 0
      background #fff
    .content
      // display flex
      padding 0
    .handleRoles
      padding 20px
      text-align center
    .roleTree,.deptsTree
      scroll()
      height calc(100% - 36px)
    .roleListTop,.deptsListTop
      width 100%
      .el-icon-user-solid
        color #afe4fa
        line-height 30px
        margin-right 5px
        // font-size 18px
      .editBox
        display flex
        .editBtn
          cursor pointer
          color: #FC713D
          float: right
          margin-left 12px
      .edit-ipt >>>.input
        // font-size 18px
      .title
        width 100%
        padding 10px 20px 0 20px
        box-sizing border-box
        background #fff
      .handle
        width 100%
        padding 20px
        box-sizing border-box
        background #fff
        border-radius 6px
        margin-bottom 10px
        >>> button
          margin-right 10px
        .search-input
          float right
          margin-right 19px
      .toApply
        color #5ab6ff
        float right
        line-height 50px
        // font-size 12px
        cursor: pointer
      .search-wrapper
        display flex
        .search-item
          display flex
          align-items center
          .item-name
            margin 0 15px 0 30px
            min-width 60px
            text-align right
          .name-else
            margin 0 15px 0 0
            min-width 45px
        .search-btn
          margin 0 15px 0 60px
      .add-btn
        margin 20px 0 10px
      .status-wrapper
        display flex
        align-items center
.personal-wrapper
  width 100%
  padded_box(border-box, 0 10px)
  position relative
  &.add-staff
    padded_box(border-box, 0 24px)
  .title
    height 40px
    background rgb(236,239,244)
    line-height 30px
    font-size 14px
    padded_box(border-box,5px 10px)
    margin-bottom 20px
  >>> .el-select
    width 360px
  // 角色分配菜单
  .menu-wrapper
    border 1px solid #DCDFE6
    width 420px
    padded_box(border-box, 10px)
    .tree-list
      width 100%
      margin-top 8px
// 给角色添加成员
.account-body
  width 100%
  height 100%
  font-size 12px
  overflow-y auto
  background #f2f2f6
  padded_box(border-box, 10px)
  border-radius 6px
  .account-top
    between()
    width 100%
    background #fff
    padded_box(border-box, 15px 20px)
    border-radius 6px
    margin-bottom 10px
    .filter-left
      display flex
      align-items center
      .search-input-box, .search-select-box
        width 160px
        height 30px
    .filter-right
      display flex
      align-items center
  .table-wrapper
    height calc(100% - 70px)
    background: #fff;
    box-sizing: border-box;
    padded_box(border-box, 15px 20px);
    border-radius: 6px
    >>> thead
      tr
&:first-child
          .cell
            padding 0 14px
</style>
